<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="240px" class="main-aside">
                <div class="logo-container">
                    <div class="logo-icon">
                        <el-icon size="24"><Monitor /></el-icon>
                    </div>
                    <h2>数据分析平台</h2>
                </div>
                
                <el-menu
                    :default-active="activeMenu"
                    class="el-menu-vertical"
                    @select="handleSelect"
                    :collapse="isCollapse"
                >
                    <el-menu-item index="dashboard">
                        <el-icon><DataLine /></el-icon>
                        <template #title>
                            <span>数据概览</span>
                        </template>
                    </el-menu-item>
                    
                    <el-sub-menu index="data">
                        <template #title>
                            <el-icon><Collection /></el-icon>
                            <span>数据管理</span>
                        </template>
                        <el-menu-item index="data-sources">数据源管理</el-menu-item>
                        <el-menu-item index="data-collection">数据采集</el-menu-item>
                        <el-menu-item index="data-analysis">数据分析</el-menu-item>
                        <el-menu-item index="weibo-analysis">微博分析</el-menu-item>
                    </el-sub-menu>
                    
                    <el-menu-item index="reports">
                        <el-icon><Document /></el-icon>
                        <template #title>
                            <span>报表管理</span>
                        </template>
                    </el-menu-item>
                    
                    <el-menu-item index="settings">
                        <el-icon><Setting /></el-icon>
                        <template #title>
                            <span>系统设置</span>
                        </template>
                    </el-menu-item>
                </el-menu>
                
                <div class="aside-footer">
                    <el-button 
                        :icon="isCollapse ? 'Expand' : 'Fold'"
                        circle
                        @click="toggleCollapse"
                    />
                </div>
            </el-aside>
            
            <el-container>
                <el-header height="64px" class="main-header">
                    <div class="header-left">
                        <el-breadcrumb>
                            <el-breadcrumb-item>首页</el-breadcrumb-item>
                            <el-breadcrumb-item>{{ currentRoute }}</el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                    
                    <div class="header-right">
                        <el-space>
                            <el-button circle icon="Search" />
                            <el-button circle icon="Bell" />
                            <el-dropdown @command="handleCommand" trigger="click">
                                <div class="user-dropdown">
                                    <el-avatar :size="32" :src="userAvatar">
                                        {{ currentUser?.username?.charAt(0).toUpperCase() }}
                                    </el-avatar>
                                    <span class="username">{{ currentUser?.username }}</span>
                                    <el-icon><CaretBottom /></el-icon>
                                </div>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="profile">
                                            <el-icon><User /></el-icon>个人资料
                                        </el-dropdown-item>
                                        <el-dropdown-item command="settings">
                                            <el-icon><Setting /></el-icon>系统设置
                                        </el-dropdown-item>
                                        <el-dropdown-item divided command="logout">
                                            <el-icon><SwitchButton /></el-icon>退出登录
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </el-space>
                    </div>
                </el-header>
                
                <el-main class="main-content">
                    <router-view v-slot="{ Component }">
                        <transition name="fade" mode="out-in">
                            <component :is="Component" />
                        </transition>
                    </router-view>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
    Monitor,
    DataLine,
    Collection,
    TrendCharts,
    Document,
    Setting,
    Search,
    Bell,
    User,
    CaretBottom,
    SwitchButton,
    Expand,
    Fold
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { 
    CanvasRenderer,
    SVGRenderer 
} from 'echarts/renderers'
import { 
    LineChart, 
    BarChart, 
    PieChart 
} from 'echarts/charts'
import {
    GridComponent,
    TooltipComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { analysisApi } from '@/api/analysis'

const store = useStore()
const router = useRouter()
const route = useRoute()
const isCollapse = ref(false)
const activeMenu = ref('dashboard')
const userAvatar = ref('')
const timeRange = ref('week')
const loading = ref(true)

const currentUser = computed(() => store.getters.currentUser)
const routeNameMap = {
    'dashboard': '数据概览',
    'data-sources': '数据源管理',
    'data-collection': '数据采集',
    'data-analysis': '数据分析',
    'weibo-analysis': '微博分析',
    'visualization': '可视化',
    'reports': '报表管理',
    'settings': '系统设置',
    'profile': '个人资料'
}

const currentRoute = computed(() => {
    const path = route.path.substring(1) || 'dashboard'
    return routeNameMap[path] || path
})

const toggleCollapse = () => {
    isCollapse.value = !isCollapse.value
}

onMounted(async () => {
    try {
        await store.dispatch('fetchUserProfile')
        await store.dispatch('fetchUserPreferences')
    } catch (error) {
        console.error('获取用户信息失败:', error)
    }
})

const handleCommand = (command) => {
    switch (command) {
        case 'profile':
            router.push('/profile')
            break
        case 'settings':
            router.push('/settings')
            break
        case 'logout':
            store.dispatch('logout')
            router.push('/login')
            ElMessage.success('已退出登录')
            break
    }
}

const handleSelect = (index) => {
    switch (index) {
        case 'dashboard':
            router.push('/')
            break
        case 'data-sources':
            router.push('/data-sources')
            break
        case 'data-collection':
            router.push('/data-collection')
            break
        case 'data-analysis':
            router.push('/data-analysis')
            break
        case 'weibo-analysis':
            router.push('/weibo-analysis')
            break
        case 'visualization':
            router.push('/visualization')
            break
        case 'reports':
            router.push('/reports')
            break
        case 'settings':
            router.push('/settings')
            break
    }
}

// 统计数据
const statistics = ref({
    totalData: 0,
    totalEngagement: 0,
    activeUsers: 0,
    engagementRate: 0,
    dataGrowth: 0,
    engagementGrowth: 0,
    userGrowth: 0,
    rateGrowth: 0,
    runningTasks: 0,
    taskProgress: 0,
    systemStatus: '正常',
    systemLoad: 0
})

// 趋势数据
const trendData = ref({
    dates: [],
    data: [],
    engagement: [],
    growth: 0
})

// 来源分布数据
const sourceData = ref({
    labels: [],
    data: []
})

// 注册必需的组件
use([
    CanvasRenderer,
    SVGRenderer,
    LineChart,
    BarChart,
    PieChart,
    GridComponent,
    TooltipComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent
])

// 趋势图表配置
const trendChartOption = computed(() => ({
    title: {
        text: '数据趋势分析',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {
        data: ['数据量', '互动量'],
        bottom: '0%'
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
    },
    xAxis: {
        type: 'category',
        data: trendData.value.dates || [],
        axisLabel: {
            rotate: 45
        }
    },
    yAxis: [
        {
            type: 'value',
            name: '数据量',
            position: 'left'
        },
        {
            type: 'value',
            name: '互动量',
            position: 'right'
        }
    ],
    series: [
        {
            name: '数据量',
            type: 'bar',
            data: trendData.value.data || [],
            yAxisIndex: 0
        },
        {
            name: '互动量',
            type: 'line',
            data: trendData.value.engagement || [],
            yAxisIndex: 1
        }
    ]
}))

// 来源分布图表配置
const sourceChartOption = computed(() => {
    const baseOption = {
        ...defaultChartOption,
        title: { text: '数据来源分布' },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        series: [
            {
                type: 'pie',
                radius: '50%',
                data: []
            }
        ]
    }

    if (!sourceData.value?.labels?.length) {
        return baseOption
    }

    const data = sourceData.value.labels.map((label, index) => ({
        name: label,
        value: sourceData.value.data[index] || 0
    }))

    return {
        ...baseOption,
        series: [
            {
                ...baseOption.series[0],
                data
            }
        ]
    }
})

// 获取数据
const fetchData = async () => {
    loading.value = true
    try {
        // 获取仪表盘数据
        const dashboardData = await analysisApi.getDashboardStats()
        if (dashboardData && typeof dashboardData === 'object') {
            statistics.value = {
                totalData: dashboardData.total_data || 0,
                totalEngagement: dashboardData.total_engagement || 0,
                activeUsers: dashboardData.active_users || 0,
                engagementRate: dashboardData.engagement_rate || 0,
                dataGrowth: dashboardData.data_growth || 0,
                engagementGrowth: dashboardData.engagement_growth || 0,
                userGrowth: dashboardData.user_growth || 0,
                rateGrowth: dashboardData.engagement_rate_growth || 0
            }
        }

        // 获取趋势数据
        const trendResponse = await analysisApi.getTrendData({ timeRange: timeRange.value })
        if (trendResponse && typeof trendResponse === 'object') {
            trendData.value = {
                dates: trendResponse.dates || [],
                data: trendResponse.data || [],
                engagement: trendResponse.engagement || [],
                growth: trendResponse.growth || 0
            }
        }

        // 获取来源分布
        const distributionResponse = await analysisApi.getSourceDistribution()
        if (distributionResponse && typeof distributionResponse === 'object' && distributionResponse.data) {
            sourceData.value = {
                labels: distributionResponse.data.map(item => item.name) || [],
                data: distributionResponse.data.map(item => item.value) || []
            }
        }

    } catch (error) {
        console.error('Error fetching data:', error)
        ElMessage.error('获取数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 监听时间范围变化
watch(timeRange, () => {
    fetchData()
})

// 初始化
onMounted(() => {
    fetchData()
})

// 清理定时器等资源
onUnmounted(() => {
    // 清理代码
})
</script>

<style scoped>
.common-layout {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    overflow: hidden;
}

.el-container {
    width: 100%;
    height: 100%;
    display: flex;
}

.main-aside {
    background-color: #001529;
    color: #fff;
    transition: width 0.3s;
    height: 100vh;
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    position: relative;
    z-index: 2;
}

.el-container.is-vertical {
    height: 100vh;
    flex: 1;
}

.main-header {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0,21,41,0.08);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    height: 64px;
    flex-shrink: 0;
    position: relative;
    z-index: 1;
    width: 100%;
}

.main-content {
    flex: 1;
    padding: 24px;
    background-color: #f0f2f5;
    overflow-y: auto;
    height: calc(100vh - 64px);
    width: 100%;
    position: relative;
}

.logo-container {
    height: 64px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    background-color: #002140;
    flex-shrink: 0;
}

.logo-icon {
    width: 32px;
    height: 32px;
    background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.logo-container h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    background: linear-gradient(to right, #1890ff, #36cfc9);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.el-menu {
    border-right: none;
    background-color: transparent;
    flex: 1;
    overflow-y: auto;
}

.el-menu-vertical:not(.el-menu--collapse) {
    width: 240px;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.user-dropdown {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.user-dropdown:hover {
    background-color: #f5f5f5;
}

.username {
    font-size: 14px;
    color: #1f2329;
    margin-right: 4px;
}

.aside-footer {
    padding: 12px;
    display: flex;
    justify-content: center;
    background-color: #001529;
    flex-shrink: 0;
}

.el-menu-item.is-active {
    background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

:deep(.el-menu--collapse) {
    width: 64px;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
    color: rgba(255,255,255,0.65);
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
    color: #fff;
    background-color: #002140;
}

:deep(.el-menu-item.is-active) {
    color: #fff;
}

:deep(.el-sub-menu .el-menu-item) {
    background-color: #000c17;
    color: rgba(255,255,255,0.65);
}

:deep(.el-sub-menu .el-menu-item:hover) {
    color: #fff;
    background-color: #001528;
}

:deep(.el-sub-menu .el-menu-item.is-active) {
    color: #fff;
    background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
    .logo-container h2,
    .username {
        display: none;
    }
    
    .main-header {
        padding: 0 12px;
    }
    
    .main-content {
        padding: 12px;
    }
    
    .header-right {
        gap: 8px;
    }
}

.data-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.card-content {
    text-align: center;
}

.card-content h2 {
    margin: 10px 0;
    font-size: 24px;
    color: #1f2329;
}

.trend {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 5px;
}

.trend-value {
    font-weight: bold;
}

.trend-value.positive {
    color: #67c23a;
}

.trend-value.negative {
    color: #f56c6c;
}

.trend-label {
    color: #909399;
    font-size: 12px;
}

.chart-row {
    margin-top: 20px;
}

.chart-card {
    height: 100%;
}

.chart-container {
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
    .el-col {
        width: 100%;
    }
    
    .chart-container {
        height: 250px;
    }
}
</style> 